﻿#include "wubi_handler.h"
#include "scheme/wubi_scheme.h"
#include "uiserver/ui_server.h"
#include "../log_tool.h"
#include <thread>

#ifdef WIN32
#include <windows.h>
#endif

WubiHandler::WubiHandler()
    : _wubi_scheme(std::make_shared<WubiSchemeMgr>())
{
    _ui_server = std::make_shared<WubiUIServer>(_wubi_scheme);
}

WubiHandler::~WubiHandler()
{
    release();
};

void WubiHandler::getCandidates(
    const char* input_code,
    std::vector<std::string> &out_candidates)
{
    out_candidates.clear();
    
    if (input_code == nullptr || input_code[0] == '\0') return;
    _wubi_scheme->getCandidateList(input_code, out_candidates);
}


bool WubiHandler::init()
{
    if(!_wubi_scheme->init()){
        return false;
    }
    //启动ui服务线程
    std::thread ui_thread(
        [this]() {
            LOG_INFO("UI服务启动");
            _ui_server->start();
        }
    );
    ui_thread.detach();
    return true;
}

bool WubiHandler::release()
{
    _ui_server->stop();
    return _wubi_scheme->release();
}

bool WubiHandler::showUI()
{
#ifdef WIN32
    std::thread th([]() {
        ShellExecute(NULL, "open", "start_ui.bat",
                        NULL, "./", SW_HIDE);
    });
    th.detach();
#endif
    return false;
}